using System;
using System.Windows;
using System.Windows.Controls;

namespace Controls
{
    public class TextBlockEx : TextBlock
    {
        public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(object), typeof(TextBlockEx), new PropertyMetadata(null, OnValueChanged));

        public static readonly DependencyProperty StringFormatProperty = DependencyProperty.Register("StringFormat", typeof(string), typeof(TextBlockEx), new PropertyMetadata("", OnValueChanged));

        public object Value
        {
            get
            {
                return GetValue(ValueProperty);
            }
            set
            {
                SetValue(ValueProperty, value);
            }
        }

        public string StringFormat
        {
            get
            {
                return (string)GetValue(StringFormatProperty);
            }
            set
            {
                SetValue(StringFormatProperty, value);
            }
        }

        private static void OnValueChanged(object sender, DependencyPropertyChangedEventArgs args)
        {
            TextBlockEx textBlockEx = sender as TextBlockEx;
            if (textBlockEx != null && textBlockEx.Value != null)
            {
                if (textBlockEx.Value is double)
                {
                    textBlockEx.Text = ((double)textBlockEx.Value).ToString(textBlockEx.StringFormat);
                }
                else if (textBlockEx.Value is int)
                {
                    textBlockEx.Text = ((int)textBlockEx.Value).ToString(textBlockEx.StringFormat);
                }
                else if (textBlockEx.Value is TimeSpan)
                {
                    textBlockEx.Text = ((TimeSpan)textBlockEx.Value/*cast due to .constrained prefix*/).ToString().Substring(0, 8);
                }
                else
                {
                    textBlockEx.Text = textBlockEx.Value.ToString();
                }
            }
        }
    }
}
